<template>
  <div class="login">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="login-ruleForm"
    >
      <el-form-item>
        <h1>修改个人信息</h1>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" show-password autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%" @click="edit"> 保存 </el-button>
      </el-form-item>
      <el-form-item>
        <RouterLink to="/">取消修改</RouterLink>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { editUserinfo, getUser } from '@/api/api'
import { useRouter } from 'vue-router'
import { jwtDecode } from 'jwt-decode'

const router = useRouter()
const ruleFormRef = ref()

const ruleForm = reactive({
  id: '',
  username: '',
  password: '',
})

// 修改个人信息
const edit = async () => {
  let token = localStorage.getItem('token') // 获取token
  let res = await editUserinfo(ruleForm, token)

  if (res.data?.code === 200) {
    ElMessage.success('修改成功')
    localStorage.setItem('userInfo', JSON.stringify(ruleForm)) // ✅ 更新本地存储
    router.push('/')
  } else {
    ElMessage.error(res.data?.message || '修改失败')
  }
}

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' },
  ],
})

onMounted(async () => {
  const token = localStorage.getItem('token')
  const data = jwtDecode(token)
  const response = await getUser(data.id, token)
  ruleForm.id = response.data.data.id
  ruleForm.username = response.data.data.username
  ruleForm.password = response.data.data.password
})
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  background-color: rgb(210, 210, 210);

  display: flex;
  align-items: center;
  justify-content: center;

  .login-ruleForm {
    width: 300px;
    padding: 20px;
    border-radius: 10px;
    background-color: white;
  }
}
</style>
